//// 倒计时逻辑
// 设置倒计时的结束日期和时间
const countdownDate = new Date("2025-02-31T23:59").getTime();
// 更新倒计时函数
function updateCountdown() {
    const now = new Date().getTime();
    const distance = countdownDate - now;

    // 计算天、小时、分钟和秒
    const days = Math.floor(distance / (1000 * 60 * 60 * 24));
    const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    const seconds = Math.floor((distance % (1000 * 60)) / 1000);

    // 在页面上显示结果
    //document.getElementById("countdown").innerHTML = `${days}d ${hours}h ${minutes}m ${seconds}s`;
    document.querySelector(".time-countdown-day").innerHTML = (days/10)>=1 ? `<span>${days}</span>` : `<span>0${days}</span>`;
    document.querySelector(".time-countdown-hour").innerHTML = (hours/10)>=1 ?  `<span>${hours}</span>` : `<span>0${hours}</span>`;
    document.querySelector(".time-countdown-min").innerHTML = (minutes/10)>=1 ?  `<span>${minutes}</span>` : `<span>0${minutes}</span>`;
    document.querySelector(".time-countdown-sec").innerHTML = (seconds/10)>=1 ?  `<span>${seconds}</span>` : `<span>0${seconds}</span>`;

    // 如果倒计时结束
    if (distance < 0) {
        clearInterval(countdownInterval);
        document.querySelector(".time-countdown-content").innerHTML = " ";
    }
}
// 每秒更新一次倒计时
const countdownInterval = setInterval(updateCountdown, 1000);
updateCountdown();  // 立即调用一次

//// 中部导航 固定
// 获取导航栏和 Banner 的元素
const navbar = document.getElementById("landing-page-navbar");
const banner = document.getElementById("landing-page-banner-first");
const cardImages = document.getElementById("shopify-section-landing-page-card-images");

// 获取 Banner 的高度
let bannerHeight = banner.offsetHeight + cardImages.offsetHeight;
const proImgCardList = document.getElementById("pro-img-card-list");
//console.log("pro img card list: "+ proImgCardList);
if(proImgCardList != null){
  bannerHeight = bannerHeight + 40;
}

// 获取所有菜单项和内容区块
const menuItems = document.querySelectorAll(".navbar-wrap a");
const sections = document.querySelectorAll(".product-display-section");

// 监听滚动事件
window.onscroll = function() {
    let currentSection = "";
    
    if (window.scrollY > bannerHeight) {
        navbar.classList.add("fixed");
    } else {
        navbar.classList.remove("fixed");
    }

    // 检查页面滚动位置，找到在视口中的内容区域
    sections.forEach(section => {
        const sectionTop = section.offsetTop - 70; // 偏移量，确保滚动到中心附近
        if (window.scrollY >= sectionTop) {
            currentSection = section.getAttribute("id");
        }
    });

    // 更新菜单项的活动状态
    menuItems.forEach(menu => {
        menu.classList.remove("active");
        if (menu.getAttribute("href") === "#" + currentSection) {
            menu.classList.add("active");

            const targetMenuItem = menu;
            const menuOffset = targetMenuItem.offsetLeft; // 获取目标菜单项的水平位置
            navbar.scrollTo({
              left: menuOffset-10, // 滚动到该菜单项
              behavior: 'smooth' // 平滑滚动
            });
        }
    });
};
// 获取所有FAQ项
const faqItems = document.querySelectorAll(".faq-item .faq-title");
faqItems.forEach(faqTitle => {
    faqTitle.onclick = function() {
        var nextElement = faqTitle.nextElementSibling;
        if(nextElement.classList.contains('active')){
            nextElement.classList.remove('active');
        }else {
            nextElement.classList.add('active');
        }
    };
});

// 获取所有special sale 变体项
const specialVariantItems = document.querySelectorAll(".product-options .label-item-first");
specialVariantItems.forEach(vairantItem => {
    vairantItem.onclick = function() {
        //所有同级节点 移除 active
        document.querySelector(".label-item-first.active").classList.remove('active');

        //当前节点 加入 active
        if(!vairantItem.classList.contains('active')){
            vairantItem.classList.add('active');
        }

        //价格变化
        let variantPrice = vairantItem.getAttribute("data-price");
        let variantOldPrice = vairantItem.getAttribute("data-old-price");
        var priceContent = variantPrice + '<span class="old-price">' + variantOldPrice + '</span>';
        document.querySelector(".special-first-price").innerHTML = priceContent;

        //差价信息变化        
        var count_off = parseFloat(variantOldPrice.replace(/[^\d\.]/g,'')) - parseFloat(variantPrice.replace(/[^\d\.]/g,''));
        count_off = count_off<0?0.00:Math.round(count_off * 100) / 100;
        var countOffStr = variantPrice.charAt(0)+count_off+' OFF';
        document.querySelector(".special-image-first").previousElementSibling.innerText = countOffStr;

        //图片变化
        if(vairantItem.getAttribute("data-image-url") != ""){
            document.querySelector(".special-image-first").setAttribute("src",vairantItem.getAttribute("data-image-url"));
        }

    };
});
//special sale first BuyNow
function buySpecialFirst(){
    var choosenItem = document.querySelector(".label-item-first.active");
    var choosenItemId = choosenItem.getAttribute("data-id");
    window.location.href = '/cart/'+choosenItemId+':1';
}

// 获取所有special sale Second 变体项
const secondVariantItems = document.querySelectorAll(".product-options .label-item-second");
secondVariantItems.forEach(vairantItem => {
    vairantItem.onclick = function() {
        //所有同级节点 移除 active
        document.querySelector(".label-item-second.active").classList.remove('active');

        //当前节点 加入 active
        if(!vairantItem.classList.contains('active')){
            vairantItem.classList.add('active');
        }

        //价格变化
        let variantPrice = vairantItem.getAttribute("data-price");
        let variantOldPrice = vairantItem.getAttribute("data-old-price");
        var priceContent = variantPrice + '<span class="old-price">' + variantOldPrice + '</span>';
        document.querySelector(".special-second-price").innerHTML = priceContent;

        //差价信息变化        
        var count_off = parseFloat(variantOldPrice.replace(/[^\d\.]/g,'')) - parseFloat(variantPrice.replace(/[^\d\.]/g,''));
        count_off = count_off<0?0.00:Math.round(count_off * 100) / 100;
        var countOffStr = variantPrice.charAt(0)+count_off+' OFF';
        document.querySelector(".special-image-second").previousElementSibling.innerText = countOffStr;

        //图片变化
        if(vairantItem.getAttribute("data-image-url") != ""){
            document.querySelector(".special-image-second").setAttribute("src",vairantItem.getAttribute("data-image-url"));
        }
    };
});

//special sale second BuyNow
function buySpecialSecond(){
    var choosenItem = document.querySelector(".label-item-second.active");
    var choosenItemId = choosenItem.getAttribute("data-id");
    window.location.href = '/cart/'+choosenItemId+':1';
}

function productSelectChange(ele) {
    console.log("changed.");
    var selectedOption = ele.options[ele.selectedIndex];
    
    //价格变化
    let optionPrice = selectedOption.getAttribute("data-price");
    let optionOldPrice = selectedOption.getAttribute("data-old-price");
    var priceContent = optionPrice + '<span class="old-price">' + optionOldPrice + '</span>';
    var nextPriceElement = ele.nextElementSibling;
    nextPriceElement.innerHTML = priceContent;

    //差价信息变化        
    var count_off = parseFloat(optionOldPrice.replace(/[^\d\.]/g,'')) - parseFloat(optionPrice.replace(/[^\d\.]/g,''));
    count_off = count_off<0?0.00:Math.round(count_off * 100) / 100;
    var countOffStr = optionPrice.charAt(0)+count_off;
    ele.parentElement.previousElementSibling.previousElementSibling.innerText = countOffStr;

    //图片变化
    if(selectedOption.getAttribute("data-image-url") != ""){
        var imgEle = ele.parentElement.previousElementSibling;
        imgEle.setAttribute("src",selectedOption.getAttribute("data-image-url"));
    }

    //选中
    selectedOption.setAttribute("selected",true);
}

function buyNowProductItem(ele) {
    var productSelectEle = ele.parentElement.previousElementSibling.children[2];
    var selectedOption = productSelectEle.options[productSelectEle.selectedIndex];
    var choosenItemId = selectedOption.getAttribute("data-id");
    window.location.href = '/cart/'+choosenItemId+':1';
}
